<template>
  <div class="dashboard-container">
    <div class="app-container">
      <el-card>
        <el-tabs>
          <!-- 放置页签 -->
          <el-tab-pane label="角色管理">
            <!-- 新增角色按钮 -->
            <el-row style="height:60px">
              <el-button
                icon="el-icon-plus"
                size="small"
                type="primary"
                @click="isShowDialog = true"
              >新增角色</el-button>
            </el-row>
            <!-- 表格 -->
            <el-table border="" :data="roleList">
              <el-table-column label="序号" width="120" type="index" />
              <el-table-column label="角色名称" width="240" prop="name" />
              <el-table-column label="描述" prop="description" />
              <el-table-column label="操作">
                <!-- 作用域插槽获取表格渲染时的当前行数据
                row 字段名不能改, 是 element 封装表格指定, 可以在文档当中查到 -->
                <template #default="{row}">
                  <el-button size="small" type="success" @click="assignPerm(row.id)">分配权限</el-button>
                  <el-button size="small" type="primary" @click="updateRole(row.id)">编辑</el-button>
                  <el-button size="small" type="danger" @click="delRole(row.id)">删除</el-button>
                </template>
              </el-table-column>
            </el-table>
            <!-- 分页组件 -->
            <el-row type="flex" justify="center" align="middle" style="height: 60px">
              <!-- 分页组件 -->
              <el-pagination
                layout="prev,pager,next"
                :total="total"
                :page-size="pageSetting.pagesize"
                @current-change="currentChange"
              />
            </el-row>
          </el-tab-pane>
          <el-tab-pane label="公司信息">
            <el-alert
              title="对公司名称、公司地址、营业执照、公司地区的更新，将使得公司资料被重新审核，请谨慎修改"
              type="info"
              show-icon
              :closable="false"
            />
            <el-form label-width="120px" style="margin-top:50px">
              <el-form-item label="公司名称">
                <el-input v-model="companyInfo.name" disabled style="width:400px" />
              </el-form-item>
              <el-form-item label="公司地址">
                <el-input v-model="companyInfo.companyAddress" disabled style="width:400px" />
              </el-form-item>
              <el-form-item label="邮箱">
                <el-input v-model="companyInfo.mailbox" disabled style="width:400px" />
              </el-form-item>
              <el-form-item label="备注">
                <el-input v-model="companyInfo.remarks" type="textarea" :rows="3" disabled style="width:400px" />
              </el-form-item>
            </el-form>
          </el-tab-pane>

        </el-tabs>
      </el-card>

      <el-dialog :title="`${formData.id?'编辑':'新增'}角色`" :visible="isShowDialog" @close="btnCancel">
        <el-form ref="addRole" :model="formData" :rules="rules">
          <el-form-item label="角色名称" prop="name">
            <el-input v-model="formData.name" />
          </el-form-item>
          <el-form-item label="角色描述" prop="description">
            <el-input v-model="formData.description" />
          </el-form-item>
        </el-form>
        <template #footer>
          <el-button size="small" type="primary" @click="btnOK">确定</el-button>
          <el-button size="small" @click="btnCancel">取消</el-button>
        </template>
      </el-dialog>

      <el-dialog title="分配权限" :visible="isShowPermission" @close="btnPermCancel">
        <!-- data 是数据数组, 套着一堆对象 props 指定要显示的字段,
        default-expand-all 默认展开所有 -->
        <el-checkbox-group v-model="checkedPerm">
          <!-- 本来多个多选框需要自己 v-for 遍历, 但是这里由树形处理了 -->
          <el-tree
            :data="permissionList"
            :props="{label: 'name'}"
            default-expand-all
            :expand-on-click-node="false"
          >
            <template #default="{data}">
              <!-- 每个属性节点都是一个多选框 -->
              <el-checkbox :label="data.id">
                {{ data.name }}
              </el-checkbox>
            </template>
          </el-tree>

        </el-checkbox-group>
        <template #footer>
          <el-button size="small" type="primary" @click="btnPermOK">确定</el-button>
          <el-button size="small" @click="btnPermCancel">取消</el-button>
        </template>
      </el-dialog>
    </div>
  </div>
</template>

<script>
import { getPermissionList } from '@/api/permission'
import { listToTreeData } from '@/utils'
import {
  delRole,
  getCompanyInfo,
  getRoleList,
  addRole,
  getRoleDetailById,
  updateRole,
  assignPerm
} from '@/api/setting'
export default {
  data() {
    return {
      roleId: '',
      permissionList: [],
      checkedPerm: [],
      isShowPermission: false,
      companyInfo: {},
      roleList: [],
      pageSetting: {
        page: 1,
        pagesize: 2
      },
      total: 0,
      isShowDialog: false,
      formData: {
        name: '',
        description: ''
      },
      rules: {
        name: [
          { required: true, message: '该项不能为空', trigger: 'blur' }
        ],
        description: [
          { required: true, message: '该项不能为空', trigger: 'blur' }
        ]
      }
    }
  },
  async created() {
    this.getCompanyInfo()
    this.getRoleList()
    this.permissionList = listToTreeData(await getPermissionList(), '0')
  },
  methods: {
    async btnPermOK() {
      // 发请求
      await assignPerm({
        id: this.roleId,
        permIds: this.checkedPerm
      })
      // 提示用户
      this.$message.success('操作成功')
      // 关闭弹窗
      this.isShowPermission = false
    },
    btnPermCancel() {
      // 清理数据
      this.checkedPerm = []
      // 关闭弹窗
      this.isShowPermission = false
    },
    async assignPerm(id) {
      // 每当设置权限的弹窗出现
      // 都要先获取当前点击角色的旧数据,回显多选框
      const { permIds } = await getRoleDetailById(id)
      this.checkedPerm = permIds
      // 弹窗时需要记录当前角色 id 方便后面发更新请求
      this.roleId = id
      this.isShowPermission = true
    },
    async getCompanyInfo() {
      this.companyInfo = await getCompanyInfo(this.$store.state.user.profile.companyId)
    },
    async getRoleList() {
      const { rows, total } = await getRoleList(this.pageSetting)
      this.roleList = rows
      this.total = total
    },
    currentChange(newPage) {
      this.pageSetting.page = newPage
      this.getRoleList()
    },
    async delRole(id) {
      try {
        // 二次询问
        await this.$confirm('确定删除吗?')
        // 发请求
        await delRole(id)
        // 提示用户
        this.$message.success('删除成功')
        // 更新页面
        this.getRoleList()
      } catch (error) {
        console.log(error)
      }
    },
    async btnOK() {
      // 校验表单
      await this.$refs.addRole.validate()
      // 发请求
      // 这里需要判断是编辑还是新增
      // 主要依赖 this.formData.id 是否存在
      if (this.formData.id) {
        // 编辑
        await updateRole(this.formData)
      } else {
        // 新增
        await addRole(this.formData)
      }
      // 提醒用户
      this.$message.success('操作成功')
      // 刷新数据
      this.getRoleList()
      // 关闭弹窗
      this.isShowDialog = false
    },
    btnCancel() {
      // 清理绑定过的数据, 还有表单报错
      // resetFields 只能清理绑定过的默认数据,
      // 需要手痛清理其他数据才行
      this.formData = {
        name: '',
        description: ''
      }
      this.$refs.addRole.resetFields()
      this.isShowDialog = false
    },
    async updateRole(id) {
      this.formData = await getRoleDetailById(id)
      this.isShowDialog = true
    }
  }
}
</script>

<style>

</style>
